class Solution {
public:
    class cmp{
    public:
        bool operator()(pair<int,int>& a,pair<int,int>& b){
            return a.first > b.first;
        }
    };                              
    int eatenApples(vector<int>& apples, vector<int>& days) {
        int n = apples.size();
        priority_queue<pair<int,int>,vector<pair<int,int>>,cmp> q;
        
        q.emplace(days[0]-1,apples[0]);
        
        int ans = 0;
        int i = 0;
        while(!q.empty() || i < n){
            while(!q.empty() && q.top().first < i) q.pop();
            if(!q.empty()){
                auto p = q.top();
                q.pop();
                if(p.second > 0){
                    ans++;
                    p.second--;
                }
                if(p.second > 0) q.push(p);
            }
            i++;
            if(i < n && apples[i] > 0){
                q.emplace(i+days[i]-1,apples[i]);
            }
        }
        return ans;
    }
};
